package cn.oveay.classdesign.controller.servlet;

import cn.oveay.classdesign.bean.basebean.User;
import cn.oveay.classdesign.service.UserService;
import cn.oveay.classdesign.service.impl.UserServiceImpl;
import cn.oveay.classdesign.util.security.RSA;
import cn.oveay.classdesign.util.security.SHA;
import cn.oveay.classdesign.util.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author QiangweiLuo
 * 不考虑安全性来给出提示
 */
@WebServlet("/login")
public class LoginServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    public String forward(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie []cookies = req.getCookies();
        String name = null;
        Boolean flag = false;
        if(cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals("name")) {
                    name = RSA.deCoding(c.getValue());
                }
                if (c.getName().equals("sec")) {
                    flag = true;
                }
            }
        }
        if(flag && name != null){
            User user = userService.findByName(name);
            if(user != null){
                user.setOnline(User.ONLINE);
                userService.updateUser(user);
                req.getSession().setAttribute("user", user);
                return "r:/list?method=forward";
            }
        }
        return "/WEB-INF/pages/login.html";
}

    public String login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        String check = req.getParameter("remember");
        if(checkPassword(pwd) != 0 || checkUsername(name) != 0){
            resp.getWriter().append("{\"error\":true, \"msg\":\"用户名或密码出现错误.\"}");
            return null;
        }
        User user = userService.findByName(name);
        if(user == null){
            resp.getWriter().append("{\"error\":true, \"msg\":\"用户名不存在.\"}");
            return null;
        }
        if(!user.getPwd().equals(SHA.SHA256Encoding(pwd))){
            resp.getWriter().append("{\"error\":true, \"msg\":\"密码不正确.\"}");
            return null;
        }
        if(check != null && check.equals("1")){
            Cookie cookiename = new Cookie("name", RSA.enCoding(name));
            cookiename.setMaxAge(60 * 60 * 24 * 10);
            resp.addCookie(cookiename);
            Cookie cookiese = new Cookie("sec", "　");
            cookiese.setMaxAge(60 * 60 * 24 * 10);
            resp.addCookie(cookiese);
        }
        if(user.getOnline() == User.ONLINE){
            resp.getWriter().append("{\"error\":true, \"msg\":\"您的账户已在某处登录.\"}");
            return null;
        }
        user.setOnline(User.ONLINE);
        userService.updateUser(user);
        req.getSession().setAttribute("user", user);
        resp.getWriter().append("{\"error\":false}");
        return null;
    }

    public String checkUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        Integer flag = checkUsername(name);
        switch (flag){
            case 0:
                return null;
            case 1:
                resp.getWriter().append("{\"error\":true, \"msg\":\"用户名不能为空.\"}");
                return null;
            default:
                resp.getWriter().append("{\"error\":true, \"msg\":\"未知错误.\"}");
                return null;
        }
    }

    public String logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie []cookies = req.getCookies();
        if(cookies != null) {
            for (Cookie c : cookies) {
                c.setMaxAge(0);
                resp.addCookie(c);
            }
        }
        req.getSession().invalidate();
        return "r:/login?method=forward";
    }

    public Integer checkUsername(String name){
        if("".equals(name.trim())){
            return 1;
        }
        return 0;
    }

    public String checkPassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pwd = req.getParameter("pwd");
        Integer flag = checkPassword(pwd);
        switch (flag){
            case 0:
                return null;
            case 1:
                resp.getWriter().append("{\"error\":true, \"msg\":\"密码不能为空.\"}");
                return null;
            case 2:
                resp.getWriter().append("{\"error\":true, \"msg\":\"密码长度至少为8位.\"}");
                return null;
            default:
                resp.getWriter().append("{\"error\":true, \"msg\":\"未知错误.\"}");
                return null;
        }
    }

    public Integer checkPassword(String password){
        if("".equals(password.trim())){
            return 1;
        }
        if(password.trim().length() < 8){
            return 2;
        }
        return 0;
    }
}
